package energy;

import java.io.*;
import java.util.List;

import org.apache.log4j.Logger;

public class EnergyStorage {

	private static Logger log = Logger.getLogger("energy.EnergyStorage");
	private static final String FILE_NAME_PREFIX = "energydata";
	private static final String FILE_NAME_POSTFIX = ".csv";

	FileWriter writer;
	//FlagsProcessor processor;
	private String filename;
	
	public EnergyStorage() {
		writer = null;
		//processor = null;
		filename = null;
	}
	
	public EnergyStorage(String file) {
		this();
		filename = file; 
	}
	
	public boolean open(String stateDescription) {
        try { 
        	File file;
        	if(filename==null) {
        		int i = 0;
        		do { 
        			file = new File(FILE_NAME_PREFIX + i + FILE_NAME_POSTFIX);
        			i++;
        		} while(file.exists());
        	} else {
        		file = new File(filename + FILE_NAME_POSTFIX);
        		file.delete();
        		
        	}
        	
        	writer = new FileWriter(file, true);
        	writer.write("Time;Current;"+stateDescription+"\n");
        	writer.flush();
    		return true;
		} catch(IOException e) {
			log.error("Could not open file.", e);
			return false;
		}
	}
	
	public boolean add(List<EnergyData> dataList) {
		try {
			for(int row=0; row<dataList.size(); row++) {
				EnergyData data = dataList.get(row);
				//if(processor!=null) data = processor.process(data);
				writer.write(data.time+";"+data.current+";"+data.state+";\n");
			}
			writer.flush();
			return true;
		} catch(IOException e) {
			log.error("Could not write to file.", e);
			return false;
		}	
	}
	
	public boolean add(EnergyData data) {
		try {
			//if(processor!=null) data = processor.process(data);
			writer.write(data.time+";"+data.current+";"+data.state+";\n");
			writer.flush();
			return true;
		} catch(IOException e) {
			log.error("Could not write to file.", e);
			return false;
		}	
	}
	
	public boolean add(String data) {
		String[] newData = new String[1];
		newData[0] = data;
		return add(newData);
	}
	
	public boolean add(String[] data) {
		String[][] newData = new String[1][];
		newData[0] = data;
		return add(newData);
	}
	
	public boolean add(String[][] data) {
		try {
	    	for(int i=0; i<data.length; i++) {
	    		String line = "";
	    		for(int j=0; j<data[0].length; j++) {
	    			line += data[i][j] + ";";
	    		}
	    		writer.write(line + "\n");
	    	}
		    return true;
	    } catch(IOException e) {
			log.error("Could not write to file.", e);
			return false;
		}
	}
	
	public boolean close() {
	    try {
	    	writer.flush();
		    writer.close();
		    return true;
	    } catch(IOException e) {
			log.error("Could not close file.", e);
			return false;
		}	    
	}

}
